package com.ttmusic.utils;

import com.ttmusic.activitys.R;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.net.Uri;

/**
 * 图片工具
 * @author wuchangyong
 *
 */
public class BitmapUtil {

    public static Bitmap drawable2bitamp(Drawable drawable) {
        BitmapDrawable bd = (BitmapDrawable) drawable;
        return bd.getBitmap();
    }

    @SuppressWarnings("deprecation")
	public static Drawable bitmap2drawable(Bitmap bitmap) {
        return new BitmapDrawable(bitmap);
    }
    
    /**
	 * 通过音乐文件绝对路径获取音乐内置图片
	 * @param context
	 * @param url
	 * @return
	 */
	public static Bitmap getMusicImg(Context context, String url) {
		if(null != url && !"".equals(url)) {
			Uri selectedAudio = Uri.parse(url);// the URI of audio file
			MediaMetadataRetriever myRetriever = new MediaMetadataRetriever();
			myRetriever.setDataSource(context, selectedAudio); 
			byte[] artwork = myRetriever.getEmbeddedPicture();
			
			if (artwork != null) {
				Bitmap bMap = BitmapFactory.decodeByteArray(artwork, 0, artwork.length);
				return bMap;
			} 
		}
        return BitmapFactory.decodeResource(context.getResources(), R.drawable.music_gray);
    }
	
	/**
	 * 通过本地图片名称加载本地图片
	 * @param imgName 本地图片名称
	 * @param context 当前Activity的上下文
	 * @return Bitmap
	 */
	public static Bitmap getLoacalBitmap(String imgName, Context context) {
		Resources res = context.getResources();
		if(null != imgName && !"".equals(imgName)) {
		    //去掉图片名称的后缀名
		    imgName = imgName.substring(0, imgName.indexOf("."));
		    int resID = res.getIdentifier(imgName, "drawable", context.getPackageName());
		    return BitmapFactory.decodeResource(res, resID);
		}
		return BitmapFactory.decodeResource(res, R.drawable.icon_musiclist_default);
	}
    
}
